import datetime
from typing import Any, List

from django import http
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
from django.views import View

from cdserver.utils.pagination import Pagenation
from thirdpart.mixins.mixin import IsActiveMixin

from .. import errors
from ..models import BuildRecord, ReleaseInfo


@login_required
def review_add(request, nid):
    ri = ReleaseInfo.objects.get(id=nid, deleted_at=None)
    if ri.status not in (1, 3):
        raise errors.AlreadyProcessedError(
            f"The <ReleaseInfo {ri.id}, status: {ri.status}>has been processed!"
        )
    ri.status = 2
    ri.submit_time = datetime.datetime.now()
    ri.save()
    return redirect("draft_list")


@login_required
def review_list(request):
    """发版草稿查询"""
    queryset = ReleaseInfo.objects.filter(status=2, deleted_at=None)
    page_object = Pagenation(request, queryset)
    context = {
        "object_list": page_object.page_queryset,
        "page_string": page_object.html(),
    }
    return render(request, "draft/review_list.html", context)


class ReviewAgreeView(IsActiveMixin, View):
    http_method_names: List[str] = ["get"]

    def dispatch(
        self, request: http.HttpRequest, *args: Any, **kwargs: Any
    ) -> http.HttpResponse:
        if not request.user.is_superuser:
            return self.handle_no_permission()
        ri = ReleaseInfo.objects.get(id=kwargs.get("nid"), deleted_at=None)
        if ri.status != 2:
            raise errors.ErrorStatus(f"{ri} status error. ")
        ri.status = 4
        ri.save()

        from django_q.tasks import async_task

        from ..builder import remote_build

        b = BuildRecord.objects.create(
            release_info=ri,
            version=ri.release_version,
        )
        task_id = async_task(remote_build, ri.product.server.id, b, ri)
        ri.task_id = task_id
        b.task_id = task_id
        ri.save()

        return redirect("release_list")


class ReviewDisagree(IsActiveMixin, View):
    http_method_names: List[str] = ["get"]

    def dispatch(self, request, nid, *args, **kwargs):
        if not request.user.is_superuser:
            return self.handle_no_permission()
        ri = ReleaseInfo.objects.get(id=nid, deleted_at=None)
        if ri.status != 2:
            raise errors.ErrorStatus(f"{ri} status error. ")
        ri.status = 3
        ri.save()
        return redirect("draft_list")
